/**
 * Project Name:mauto-web
 * File Name:ApiInterceptor.java
 * Package Name:com.inftech.mauto.sys.interceptor
 * Date:2016年11月1日下午4:10:42
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.sys.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONObject;
import com.inftech.mauto.common.constant.HttpStatusCodeEnum;
import com.inftech.mauto.common.constant.SessionConstEnum;
import com.inftech.mauto.sys.entity.ResultJson;
import com.mingsoft.base.constant.e.BaseEnum;
import com.mingsoft.basic.interceptor.BaseInterceptor;
import com.mingsoft.weixin.dao.IWeixinDao;
import com.mingsoft.weixin.entity.WeixinEntity;
import com.mingsoft.weixin.util.OauthUtils;

/**
 * ClassName:ApiInterceptor <br/>
 * Function: API调用拦截器. <br/>
 * Date: 2016年11月1日 下午4:10:42 <br/>
 * 
 * @author puyf
 * @version
 * @since JDK 1.7
 */
public class ApiInterceptor extends BaseInterceptor {

	/**
	 * 注入微信持久化层
	 */
	@Autowired
	private IWeixinDao weixinDao;

	/**
	 * 后台服务器地址
	 */
	@Value("${adminUrl}")
	private String adminUrl;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// session判断
		if (this.getSession(request, SessionConstEnum.PEOPLE_SESSION) == null) {
			// 不存在session

			// 获取微信信息
			WeixinEntity weixin = weixinDao.getEntity(null, null, null);
			OauthUtils oauthUtils = new OauthUtils(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());

			// 未取得code，重定向至授权请求
			String fullUrl = adminUrl + "oauth/wxlogin";

			String codeUrl = oauthUtils.getCodeUrl(weixin.getWeixinAppID(), fullUrl, true, null);

			HttpStatusCodeEnum statusCode = HttpStatusCodeEnum.STATUS_CODE_401;
			this.outJson(response, statusCode, false, statusCode.toString(), codeUrl);
			logger.warn("用户未登录");
			return false;
		} else {
			// 存在session，进行相关业务
			return true;
		}
	}

	private void outJson(HttpServletResponse response, BaseEnum code, boolean flag, String msg, Object data) {
		try {
			response.setContentType("application/json;charset=utf-8");
			ResultJson result = new ResultJson();
			if (code != null) {
				result.setCode(String.valueOf(code.toInt()));
			}
			result.setResult(flag);
			result.setResultMsg(msg);
			result.setResultData(data);
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSONObject.toJSON(result));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
